﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace RabbitMQClient.DependencyInjection
{
    public static class RabbitMQServiceCollectionExtensions
    {
        /// <summary>
        /// 依赖注入使用RabbitMQ
        /// </summary>
        /// <param name="services"></param>
        public static IServiceCollection AddRabbitMQ(this IServiceCollection services)
        {
            services.AddTransient<IRabbitMQClient, RabbitMQClient>(x =>
            {
                var configuration = x.GetService<IConfiguration>();
                return new RabbitMQClient(configuration);
            });

            return services;
        }

        public static void RegisterRabbitMQInvoker(this IServiceCollection services)
        {
            var configuration = services.BuildServiceProvider().GetService<IConfiguration>();

            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes().Where(t => t.BaseType != null &&
                                                         (t.BaseType.Name == typeof(WorkQueuesBase<>).Name
                                                          || t.BaseType.Name == typeof(PublishSubscribeBase<>).Name
                                                          || t.BaseType.Name == typeof(RpcServerBase<,>).Name)
                )).ToArray();
            foreach (var type in types)
            {
                services.AddSingleton(type);
                var queue = services.BuildServiceProvider().GetService(type) as QueueBase;
                queue.Execute();
            }
        }
    }
}